package com.base.service.business;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import org.springframework.util.CollectionUtils;

import com.base.enums.ResultStatus;
import com.base.model.product.ProductDataItemResult;
import com.base.model.product.ProductDto;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ProductDataBusiness implements Callable<List<ProductDataItemResult>> {

	@Override
	public List<ProductDataItemResult> call() throws Exception {
		List<ProductDataItemResult> results = null;
		if (!CollectionUtils.isEmpty(dtoList)) {
			results = new ArrayList<ProductDataItemResult>(dtoList.size());
			for (ProductDto dto : dtoList) {
				log.info("此次处理数量:{},批次号:{}",dtoList.size(),dto.getProductDataItem().getCHARG());
				ProductDataItemResult result = new ProductDataItemResult();
				try {
					result.setCHARG(dto.getProductDataItem().getCHARG());
					productDataService.save(dto);
				} catch (Exception e) {
					log.error("添加单品数据失败", e);
					result.setZSUCCESS(ResultStatus.E.getValue());
					result.setZMESSAGE(this.getMessage(e));
				}
				results.add(result);
			}
		}
		return results;
	}

	
	
	private String getMessage(Exception e) {
		String message = "";
		if (e.getCause() == null) {
			message = e.getMessage();
		} else {
			message = e.getCause().getMessage();
			if (message.contains("无法将 NULL")) {
				message = "必填字段不能为空";
			} else if (message.contains("\n")) {
				message = message.substring(message.indexOf(":") + 1, message.indexOf("\n"));
			} else {
				message = e.getCause().getMessage().replace("\n", "");
			}
		}
		return message;
	}
	
	private List<ProductDto> dtoList;

	private ProductDataService productDataService;
	
	public List<ProductDto> getDtoList() {
		return dtoList;
	}

	public void setDtoList(List<ProductDto> dtoList) {
		this.dtoList = dtoList;
	}

	public ProductDataService getProductDataService() {
		return productDataService;
	}

	public void setProductDataService(ProductDataService productDataService) {
		this.productDataService = productDataService;
	}


	
	

}
